package com.ee.chat.common.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ee.chat.common.bean.Result;
import com.ee.chat.common.dao.HostMapper;
import com.ee.chat.common.dao.SysPushMessageMapper;
import com.ee.chat.common.entity.Host;
import com.ee.chat.common.entity.SysPushMessage;
import com.ee.chat.common.serconfig.MyPushConfig;
import com.ee.chat.common.service.IPushMessageService;
import com.ndhutu.ee.util.push.jg.PushUtil;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author Shane
 * @Date 2019/10/22 22:29
 */
@Service
public class PushMessgaeServiceImpl implements IPushMessageService {
    @Resource
    SysPushMessageMapper sysPushMessageMapper;
    @Resource
    MyPushConfig pushConfig;
    @Resource
    HostMapper hostMapper;

    /**
     * 获取最新消息
     * @Author Shane
     * @Date 2020/1/30 23:29
     * @param
     * @return
     */
    @Override
    public Result getNewestPushMessage(Integer userId) throws Exception {
        Map<String, Object> data = new HashMap<>();

        Host host = hostMapper.selectByUserId(userId);
        SysPushMessage message = sysPushMessageMapper.getNewestPushMessage(userId, host == null ? 0 : 1);
        Map<String, Object> messageMap = new HashMap<>();
        if(message != null){
            messageMap = JSON.parseObject(JSON.toJSONString(message), new TypeReference<Map<String, Object>>(){});
            Map<String, Object> dataMap = JSONObject.parseObject(message.getData());
            messageMap.put("data", dataMap);
        }
        data.put("message", messageMap);

        int count = sysPushMessageMapper.getUserNotReadPushMessageCount(userId);
        data.put("notRead", count);

        return Result.returnSuccess(data);
    }

    /**
     * 获取推送消息
     * @Author Shane
     * @Date 2019/10/22 22:31
     * @param
     * @return
     */
    @Override
    public Result getPushMessage(Integer userId, Integer page, Integer limit) throws Exception {
        Map<String, Object> data = new HashMap<>();

        Host host = hostMapper.selectByUserId(userId);
        Page<Map<String, Object>> p = new Page<>(page, limit);
        IPage<SysPushMessage> iPage = sysPushMessageMapper.getPushMessgae(p, userId, host == null ? 0 : 1);
        List<SysPushMessage> messages = iPage.getRecords();
        List<Map<String, Object>> messageMaps = new ArrayList<>();
        for(SysPushMessage message : messages){
            Map<String, Object> messageMap = JSON.parseObject(JSON.toJSONString(message), new TypeReference<Map<String, Object>>(){});
            Map<String, Object> dataMap = JSONObject.parseObject(message.getData());
            messageMap.put("data", dataMap);
            messageMaps.add(messageMap);
        }

        data.put("messages", messageMaps);

        int count = sysPushMessageMapper.getUserNotReadPushMessageCount(userId);
        data.put("notRead", count);

        List<Integer> ids = new ArrayList<>();
        for(SysPushMessage message : messages){
            ids.add(message.getId());
        }
        if(ids.size() > 0){
            sysPushMessageMapper.batchUpdateIsRead(ids);
        }

        return Result.returnSuccess(data);
    }

    @Override
    public Result cleanPushMessage(Integer userId) throws Exception {
        QueryWrapper<SysPushMessage> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        SysPushMessage entity = new SysPushMessage();
        entity.setIsDelete(1);
        sysPushMessageMapper.update(entity, wrapper);

        return Result.returnSuccess(null);
    }

    /**
     * 推送群消息
     * @Author Shane
     * @Date 2019/10/22 23:00
     * @param
     * @return
     */
    @Override
    public void pushGroupMessage(String title, String content, Map<String, String> data) throws Exception{
        PushUtil.push("user", null, title, content, data, pushConfig);

        SysPushMessage sysPushMessage = new SysPushMessage(0, 0, title, content, JSONObject.toJSONString(data), 0);
        sysPushMessageMapper.insert(sysPushMessage);
    }

    /**
     * 推送新用户注册消息(定时一分钟后执行)
     * @Author Shane
     * @Date 2019/10/23 0:09
     * @param
     * @return
     */
    @Override
    @Async
    public void pushNewUserMessage(Integer userId) throws Exception {
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                //新用户通知
                String title = "恭喜注册成为新用户";
                String content = "恭喜注册成为新用户";
                int type = 0;
                Map<String, String> data = new HashMap<>();
                data.put("title", title);
                data.put("content", content);
                data.put("type", type+"");

                PushUtil.push(null, userId+"", title, content, data, pushConfig);

                SysPushMessage sysPushMessage = new SysPushMessage(1, userId, title, content, JSONObject.toJSONString(data), type);
                sysPushMessageMapper.insert(sysPushMessage);


               /* //消息说明
                title = "私信招呼说明";
                content = "  为什么这么多女的给我发私信招呼？？？\n" +
                        "  对于刚玩PP交友的朋友们为什么这么多女的给我发信息，是不是机器人？是不是假的？这辈子都没见过这么主动的...\n" +
                        "  不必担心，首先：PP交友是一款基于有偿视频聊天的 社交APP，聊天过程中，付费方需消耗PP，收费方可获取积分，PP交友的这种奖励体系改变了以往女生高冷，被动，被追逐的交友状态，所以女神们就会主动跟您发私信。 \n" +
                        "  再者：当您一登录PP交友，系统就会自动把您匹配推荐给在线认证女神，女神就会主动给您私信招呼，这就是为什么在PP交友， 女神那么主动的原因。\n" +
                        "  所以别怀疑。全部都是认证的真人在线的。没有一个机器人放心交友吧！";
                data.put("title", title);
                data.put("content", content);
                data.put("type", type+"");
                PushUtil.push(null, userId+"", title, content, data, pushConfig);
                PushUtil.push(null, userId+"", title, content, data, pushConfig2);

                sysPushMessage = new SysPushMessage(1, userId, title, content, JSONObject.toJSONString(data), type);
                sysPushMessageMapper.insert(sysPushMessage);*/
            }
        }, 1*3600);

    }

    /**
     * 推送一般消息
     * @Author Shane
     * @Date 2019/12/17 20:13
     * @param
     * @return
     **/
    @Override
    @Async
    public void pushGeneralMessage(Integer userId, Map<String, String> data) throws Exception {
        PushUtil.push(null, userId+"", data.get("title"), data.get("content"), data, pushConfig);

        SysPushMessage sysPushMessage = new SysPushMessage(1, userId, data.get("title"), data.get("content"), JSONObject.toJSONString(data), Integer.parseInt(data.get("type")));
        sysPushMessageMapper.insert(sysPushMessage);

    }
}
